package com.open.loan.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.open.loan.config.OSS.AliyunOSS;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);


    public static String upload(File file){
        logger.info("=========>OSS文件上传开始："+file.getName());
        String endpoint=AliyunOSS.endpoint;
        String accessKeyId=AliyunOSS.accessKeyId;
        String accessKeySecret=AliyunOSS.accessKeySecret;
        String bucketName=AliyunOSS.bucketName;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            ByteArrayOutputStream out = null;
            BASE64Decoder decoder = new BASE64Decoder();
            FileInputStream in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) != -1) {
                out.write(b, 0, b.length);
            }

            ByteArrayInputStream stream = new ByteArrayInputStream(b);

            //创建文件路径
            String fileUrl = "file/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(bucketName,file.getName(),stream);
            //ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);

            final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;
            long time = System.currentTimeMillis() + duration;
            Date expiration = new Date(time);
            URL url=ossClient.generatePresignedUrl(bucketName,file.getName(), expiration);

            if(null != result){
                logger.info("==========>OSS文件上传成功,OSS地址："+fileUrl);
                return url.toString();
            }
        }catch (OSSException oe){
            logger.error(oe.getMessage());
        }catch (ClientException ce){
            logger.error(ce.getMessage());
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
}
